import React, { Fragment, useState, useEffect, isValidElement } from "react";
import appStyle from "./App.module.scss";
import Logo from "./assets/images/logo.svg";
import Robot from "./components/Robot";
import ShopingCart from "./components/ShoppingCart";
import RobotDescount from "./components/RobotDescount";
import { selector, useRecoilValue } from "recoil";
const currentFetchData = selector({
  key: "roboteListData",
  get: async ({ get }) => {
    const res = await fetch("https://jsonplaceholder.typicode.com/users");
    const data = await res.json();
    if (data.error) {
      throw data.error;
    }
    return data;
  },
});
const obj = <span>123</span>
console.log(isValidElement(obj));
// const useRobotes = () => {
//   const loadable = useRecoilValueLoadable(currentFetchData);
//   switch (loadable.state) {
//     case "hasValue":
//       return loadable.contents;
//     case "loading":
//       return <div>Loading...</div>;
//     case "hasError":
//       return loadable.errorMaybe();
//     default:
//       break;
//   }
// };
// 函数组件
interface Props {}
const App: React.FC<Props> = (props) => {
  const robote = useRecoilValue(currentFetchData) as Array<any>;
  const [count, setCount] = useState(0);
  const [list, setList] = useState([
    [{ name: "chj", value: 123 }],
    [{ name: "asd", value: 345 }],
    [{ name: "csz", value: 789 }],
  ]);
  const point = new Date(new Date().toLocaleDateString()).getTime(); // 当天0点
  const timer = Date.now(); //当前时间
  const onHanldBtn = () => {
    if (point - timer) {
      if (count >= 3) {
        alert("当天点击次数上限，请明日再来" + count);
      } else {
        setCount((count) => count + 1);
      }
    }
  };
  useEffect(() => {
    if (point === timer) {
      setCount((count) => (count = 0));
    }
  }, [point, timer]);
  return (
    <Fragment>
      <button onClick={onHanldBtn}>点击</button>
      <ul>
        {list.map((item) => {
          return item.map((i) => {
            return <li key={i.value}>{i.name}</li>;
          });
        })}
      </ul>
      <div className={appStyle.app}>
        <div className={`${appStyle.appHeader}`}>
          <img src={Logo} alt="logo" className={appStyle.appLogo} />
          <h2>罗伯特机器人</h2>
        </div>
        <ShopingCart></ShopingCart>
        <div className={appStyle.robotList}>
          {robote.map((item, index) => {
            if (index % 2 === 0) {
              return <Robot key={item.id} {...item}></Robot>;
            } else {
              return <RobotDescount key={item.id} {...item}></RobotDescount>;
            }
          })}
        </div>
      </div>
    </Fragment>
  );
};
export default App;
